#!/bin/bash

# 设置配置主目录
if [ -z "$CONFIG_HOME" ]; then
  export CONFIG_HOME="${HOME}/.mac_sync"
fi

# 使用统一的全局包根目录结构
NODE_GLOBAL_ROOT="${HOME}/.node_global"
GROUP="middle"
NPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/npm"
PNPM_GLOBAL_DIR="${NODE_GLOBAL_ROOT}/${GROUP}/pnpm"

# 设置日志文件
LOG_FILE="${CONFIG_HOME}/logs/node_middle_setup_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "$(dirname "$LOG_FILE")"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 错误处理函数
handle_error() {
    local package=$1
    local attempt=$2
    local max_attempts=$3
    
    if [ $attempt -lt $max_attempts ]; then
        log "⚠️ 安装 $package 失败，尝试重新安装 (尝试 $attempt/$max_attempts)"
        return 1
    else
        log "❌ 安装 $package 失败，已达到最大重试次数"
        echo "$package" >> "${CONFIG_HOME}/logs/middle_failed_packages.txt"
        return 0
    fi
}

# 安装单个包的函数
install_package() {
    local package=$1
    local version=$2
    local full_package="$package"
    
    if [ ! -z "$version" ]; then
        full_package="$package@$version"
    fi
    
    local max_attempts=3
    local attempt=1
    
    while [ $attempt -le $max_attempts ]; do
        log "📦 正在安装 $full_package (尝试 $attempt/$max_attempts)"
        if pnpm add -g "$full_package" >> "$LOG_FILE" 2>&1; then
            log "✅ 成功安装 $full_package"
            return 0
        else
            handle_error "$full_package" $attempt $max_attempts || { attempt=$((attempt + 1)); continue; }
            return 1
        fi
    done
}

# 创建目录
mkdir -p "${NPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/bin"
mkdir -p "${PNPM_GLOBAL_DIR}/store"

# 设置环境变量
export NPM_CONFIG_PREFIX="${NPM_GLOBAL_DIR}"
export PATH="${NPM_GLOBAL_DIR}/bin:$PATH"

# 清理之前的失败记录
rm -f "${CONFIG_HOME}/logs/middle_failed_packages.txt"

log "开始安装适用于 Node.js 14-19 的常用全局开发工具..."

# 先安装 pnpm (使用 npm 安装)
log "🔧 开始安装 pnpm..."
npm install -g pnpm@8.15.4 >> "$LOG_FILE" 2>&1
log "✨ pnpm 安装完成"
echo "----------------------------------------"

# 配置 pnpm
export PNPM_HOME="${PNPM_GLOBAL_DIR}"
export PATH="${PNPM_HOME}/bin:$PATH"
pnpm config set global-dir "${PNPM_HOME}"
pnpm config set global-bin-dir "${PNPM_HOME}/bin" 
pnpm config set store-dir "${PNPM_HOME}/store"
log "✨ pnpm 配置完成"
echo "----------------------------------------"

# 基础开发工具
log "🔧 开始安装基础开发工具..."
install_package "typescript" "4.9.5"  # 最后支持 Node.js 14 的版本
install_package "ts-node" "10.9.1"    # 兼容 Node.js 14 的版本
install_package "nodemon" "2.0.22"
install_package "pm2" "5.3.0"
install_package "http-server" "14.1.1"
install_package "serve" "14.2.1"
install_package "json-server" "0.17.4"
install_package "npm-check-updates" "16.14.12"
log "✨ 基础开发工具安装完成"
echo "----------------------------------------"

# 前端框架 CLI
log "🔧 开始安装前端框架 CLI..."
install_package "@vue/cli" "5.0.8"
install_package "@angular/cli" "15.2.10"  # 最后支持 Node.js 14 的版本
install_package "create-react-app" "5.0.1"
install_package "create-vite" "4.4.1"
install_package "@nestjs/cli" "9.5.0"     # 兼容 Node.js 14
install_package "create-next-app" "13.5.6" # 最后支持 Node.js 14 的版本
install_package "@nuxt/create-app" "3.9.0"
install_package "gatsby-cli" "4.25.0"     # 最后支持 Node.js 14 的版本
install_package "@tarojs/cli" "3.6.19"
install_package "@ionic/cli" "7.1.5"
install_package "@quasar/cli" "2.3.0"
log "✨ 前端框架 CLI 安装完成"
echo "----------------------------------------"

# 构建工具
log "🔧 开始安装构建工具..."
install_package "yarn" "1.22.19"
install_package "webpack-cli" "4.10.0"    # 最后支持 Node.js 14 的版本
install_package "rollup" "3.29.4"         # 需要 Node.js 14.18+
install_package "esbuild" "0.18.20"       # 最后支持 Node.js 14 的版本
install_package "turbo" "1.10.16"         # 需要 Node.js 14.6+
install_package "vite" "4.4.11"           # 最后支持 Node.js 14 的版本
install_package "unbuild" "1.2.1"
install_package "swc-cli" "0.1.62"
install_package "parcel" "2.8.3"          # 使用2.8.x版本兼容 Node.js 14
log "✨ 构建工具安装完成"
echo "----------------------------------------"

# 工具链
log "🔧 开始安装工具链..."
install_package "eslint" "8.45.0"          # 需要 Node.js 14.17+
install_package "prettier" "2.8.8"         # 最后支持 Node.js 14 的版本
install_package "@typescript-eslint/cli" "5.62.0"  # 支持 Node.js 14
install_package "commitizen" "4.3.0"
install_package "cz-conventional-changelog" "3.3.0"
install_package "husky" "8.0.3"
install_package "lint-staged" "13.3.0"
install_package "stylelint" "15.10.3"      # 需要 Node.js 14.17+
install_package "postcss-cli" "10.1.0"
install_package "sass" "1.64.2"            # 最后支持 Node.js 14 的版本
install_package "less" "4.2.0"
log "✨ 工具链安装完成"
echo "----------------------------------------"

# UI 开发工具
log "🔧 开始安装 UI 开发工具..."
install_package "@storybook/cli" "7.3.2"   # 需要 Node.js 16+
install_package "plop" "3.1.2"
install_package "hygen" "6.2.11"
log "✨ UI 开发工具安装完成"
echo "----------------------------------------"

# 调试和性能工具
log "🔧 开始安装调试和性能工具..."
install_package "autocannon" "7.12.0"
install_package "clinic" "12.0.0"
install_package "lighthouse" "11.0.0"      # 需要 Node.js 14.15+
install_package "source-map-explorer" "2.5.3"
install_package "webpack-bundle-analyzer" "4.9.0"
install_package "vite-bundle-analyzer" "0.6.2" # 需要 Vite 环境
log "✨ 调试和性能工具安装完成"
echo "----------------------------------------"

# 测试工具
log "🔧 开始安装测试工具..."
install_package "jest" "29.6.1"           # 需要 Node.js 14.15+
install_package "vitest" "0.34.3"         # 需要 Node.js 14.18+
install_package "cypress" "12.17.2"       # 最后支持 Node.js 14 的版本
install_package "@playwright/test" "1.39.0" # 需要 Node.js 14.17+
install_package "@testing-library/jest-dom" "5.17.0" # 配合 Jest 29 使用
log "✨ 测试工具安装完成"
echo "----------------------------------------"

# 文档工具
log "🔧 开始安装文档工具..."
install_package "docsify-cli" "4.4.4"
install_package "vuepress" "2.0.0-beta.67" # 需要 Node.js 14.18+
install_package "typedoc" "0.24.8"         # 最后支持 Node.js 14 的版本
install_package "jsdoc" "4.0.2"
log "✨ 文档工具安装完成"
echo "----------------------------------------"

# 数据库工具
log "🔧 开始安装数据库工具..."
install_package "prisma" "4.16.2"         # 最后支持 Node.js 14 的版本
install_package "typeorm" "0.3.17"
install_package "sequelize-cli" "6.6.1"
install_package "mongosh" "1.10.6"        # 大部分版本支持 Node.js 14+
log "✨ 数据库工具安装完成"
echo "----------------------------------------"

# API 开发工具
log "🔧 开始安装 API 开发工具..."
install_package "swagger-cli" "4.0.4"
install_package "@graphql-codegen/cli" "4.0.1"
install_package "graphql" "16.8.1"        # 支持 Node.js 14+
log "✨ API 开发工具安装完成"
echo "----------------------------------------"

# 移动端开发
log "🔧 开始安装移动端开发工具..."
install_package "cordova" "12.0.0"        # 需要 Node.js 14.17+
install_package "@capacitor/cli" "5.2.3"
install_package "react-native-cli" "2.0.1"
log "✨ 移动端开发工具安装完成"
echo "----------------------------------------"

# 实用工具
log "🔧 开始安装实用工具..."
install_package "npkill" "0.11.3"
install_package "npm-why" "4.0.0"
install_package "depcheck" "1.4.7"
install_package "madge" "6.1.0"
install_package "license-checker" "25.0.1"
install_package "npm-check" "6.0.1"
install_package "localtunnel" "2.0.2"
install_package "live-server" "1.2.2"
install_package "cross-env" "7.0.3"
install_package "rimraf" "5.0.1"          # 支持 Node.js 14+
install_package "concurrently" "8.2.1"
install_package "dotenv-cli" "7.3.0"
install_package "nrm" "1.2.6"
install_package "verdaccio" "5.18.1"      # 需要 Node.js 14.17+
install_package "fx" "30.1.0"
install_package "zx" "7.2.3"              # 需要 Node.js 14.17+
log "✨ 实用工具安装完成"
echo "----------------------------------------"

# 检查是否有安装失败的包
if [ -f "${CONFIG_HOME}/logs/middle_failed_packages.txt" ]; then
    log "⚠️ 以下包安装失败："
    cat "${CONFIG_HOME}/logs/middle_failed_packages.txt" | tee -a "$LOG_FILE"
    log "您可以稍后尝试手动安装这些包"
    log "安装日志已保存到：$LOG_FILE"
else
    log "🎉 所有包安装成功！"
fi

log "🚀 Node.js 14-19 环境设置完成！"
log "📁 所有全局包已安装到: ${NODE_GLOBAL_ROOT}/${GROUP}"
log "🔍 使用 'node-global' 命令可查看当前全局包目录信息" 